package com.xzx.framework.util.http;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;

import com.xzx.framework.util.json.JsonUtil;


/**
 * 以回调方式处理返回结果
 * @author wei
 * @time 2015年11月1日 下午8:50:44
 */
public class ResponseHandler implements org.apache.http.client.ResponseHandler<Object> {
	private Class<?> clz;
	
	public ResponseHandler(){
		this(String.class);
	}
	public ResponseHandler(Class<?> clz){
		this.clz = clz;
	}
	
	
	private byte[] toByteArray(HttpEntity entity) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		InputStream is = entity.getContent();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = is.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		out.close();
		is.close();
		return out.toByteArray();
	}
	
	public Object handleResponse(HttpResponse response) throws IOException {
		HttpEntity entity = response.getEntity();
		if (entity == null) {
			throw new IOException("Entity is null.");
		}

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			if(clz == null || String.class.isAssignableFrom(clz)) {
				/**
				 * 返回字符串类型
				 **/
				return EntityUtils.toString(entity);
			} else if(byte[].class.isAssignableFrom(clz)) {
				/**
				 * 返回字节数组类型
				 **/
				return toByteArray(entity);
			} else if(HttpStringResult.class.isAssignableFrom(clz)) {
				HttpStringResult hr = new HttpStringResult();
				hr.setContent(EntityUtils.toString(entity));
				hr.setContentType(entity.getContentType().getValue());
				return hr;
			} else if(HttpByteArrayResult.class.isAssignableFrom(clz)) {
				HttpByteArrayResult hr = new HttpByteArrayResult();
				hr.setContent(toByteArray(entity));
				hr.setContentType(entity.getContentType().getValue());
				return hr;
			} else {
				/**
				 * 返回指定的其它类型
				 **/
				String res = EntityUtils.toString(entity);
				return JsonUtil.toBean(res, clz);
			}
		} else {
			throw new IOException(response.getStatusLine().toString());
		}
	}
}
